package com.smen.boot.task;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.Future;

/**
 * @author Smen Lee
 * @PROJECT_NAME myspringboot
 * @TIME 2017/1/3 10:43
 */
@Component
public class AsyncTask {
    private static Random random = new Random();

    public void oneTask() throws InterruptedException {
        System.out.println("同步任务一开始");
        long currentTime1 = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long currentTime2 = System.currentTimeMillis();
        System.out.println("----SmenLee---AsyncTask---oneTask---完成同步任务一耗时为:" + (currentTime2 - currentTime1) + "毫秒");
    }

    public void twoTask() throws InterruptedException {
        System.out.println("同步任务二开始");
        long currentTime1 = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long currentTime2 = System.currentTimeMillis();
        System.out.println("----SmenLee---AsyncTask---oneTask---完成同步任务二耗时为:" + (currentTime2 - currentTime1) + "毫秒");
    }

    @Async
    public Future<String> oneAsyncTask() throws InterruptedException {
        System.out.println("异步任务一开始");
        long currentTime1 = System.currentTimeMillis();
        Thread.sleep(random.nextInt(100000));
        long currentTime2 = System.currentTimeMillis();
        System.out.println("----SmenLee---AsyncTask---oneTask---完成异步任务一耗时为:" + (currentTime2 - currentTime1) + "毫秒");
        return new AsyncResult<>("异步任务一完成");
    }

    @Async
    public Future<String> twoAsyncTask() throws InterruptedException {
        System.out.println("异步任务二开始");
        long currentTime1 = System.currentTimeMillis();
        Thread.sleep(random.nextInt(100000));
        long currentTime2 = System.currentTimeMillis();
        System.out.println("----SmenLee---AsyncTask---oneTask---完成异步任务二耗时为:" + (currentTime2 - currentTime1) + "毫秒");
        return new AsyncResult<>("异步任务二完成");
    }
}
